package com.simpleframe.security;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class LoginFilter implements Filter {
	
	private String failUrl;
	private String allowUrl;
	private static List<String> allowUrls;
	/** 是否启动过滤,开发阶段方便测试 **/
	private static boolean isOn = true;

	public void init(FilterConfig filterConfig) throws ServletException {
		allowUrl = filterConfig.getInitParameter("allowUrl");
		failUrl = filterConfig.getInitParameter("failUrl");
	}

	public void destroy() {
		
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		
		String path = httpRequest.getServletPath();
		if(isAllowURL(path)){
			chain.doFilter(request, response);
		}else{
			User user = (User) httpRequest.getSession().getAttribute(User.USER_SESSION);
			//登录验证
			if (user != null) {
				//开启权限验证
				System.out.println("==开始权限==");
				if(isOn && path.endsWith(".shtml")) {
					System.out.println("---");
					//如果是受保护的资源
					if(AuthorityContext.isProtectResource(path)) {
						if(!AuthorityContext.verifyOperate(user.getRoleIds(), path)) {
							System.out.println("没有权限");
							noAuthorityTip(httpRequest, httpResponse);
					
						}
					}
				}
				System.out.println("权限通过");
				chain.doFilter(request, response);
			}else {
				//记录用户最后地址
				httpRequest.getSession().setAttribute(User.USER_LAST_URL,path);
				sendTargetUri(httpRequest, httpResponse);
			}
		}
	}

	private void sendTargetUri(HttpServletRequest httpRequest,
			HttpServletResponse httpResponse) throws IOException {
		httpResponse.sendRedirect(httpRequest.getAttribute("ctx")+failUrl);
	}
	
	protected boolean isAllowURL(String path) {
		if(allowUrl==null){
			return false;
		}
		if(allowUrls==null){
			allowUrls = new ArrayList<String>();
			String[] ps = allowUrl.split("\n");
			for (String p : ps) {
				p = p.trim();
				if(!"".equals(p)){
					allowUrls.add(p);
				}
			}
		}
		Iterator<String> it = allowUrls.iterator();
		while (it.hasNext()) {
			String p = it.next();
			if(path.startsWith(p)){
				return true;
			}
		}
		return false;
	}
	
    /**
     * 没有权限时，跳转至提示页面
     * @param req
     * @param res
     * @throws IOException
     */
    public void noAuthorityTip(HttpServletRequest req, HttpServletResponse res) throws IOException{
		res.sendRedirect(req.getContextPath()+"/common/403.jsp");
		return;
    }
}